﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Protogamez
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        /// <summary>
        /// SET GLOBAL VARIABLE
        /// </summary>
        OleDbConnection conn = new OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;data source=" + AppDomain.CurrentDomain.BaseDirectory + "\\Resources\\gamesdb.mdb");
        OleDbConnection dbConnection = new OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;data source=" + AppDomain.CurrentDomain.BaseDirectory + "\\Resources\\gamesdb.mdb");

        string filter = "IP";

        /// <summary>
        /// SET REFERENCIAL VARIABLE
        /// </summary>
        string sqlresult1 = "";
        string sqlresult3 = "";
        string sqlresult4 = "";
        string sqlresult5 = "";
        string sqlresult6 = "";
        string sqlresult7 = "";
        string sqlresult8 = "";
        string sqlresult9 = "";
        string sqlresult10 = "";
        string sqlresult11 = "";
        string sqlresult12 = "";
        string sqlresult13 = "";

        string sqlresultt1 = "";
        string sqlresultt2 = "";
        string sqlresultt3 = "";
        string sqlresultt4 = "";

        string savepath = "";
        string gamename = "";

        /// <summary>
        /// SET GLOBAL FUNCTION
        /// </summary>
        private void listbox_games_fill(string sql)
        {
            listbox_games.Items.Clear();

            OleDbCommand cmd = new OleDbCommand(sql, conn); conn.Open(); OleDbDataReader reader; reader = cmd.ExecuteReader();

            try
            {
                while (reader.Read())
                {
                    /// <summary>
                    ///SQL REFERENCE
                    ////// </summary>
                    //Game Name
                    listbox_games.Items.Add(reader.GetString(1).ToString());
                }
            }
            catch (Exception ex)
            { Console.WriteLine(ex.Message); return; }
            finally
            {
                reader.Close(); conn.Close();
            }

            listbox_games.SelectedIndex = 0;
        }

        private void listbox_games_result(string sql)
        {
            OleDbCommand cmd = new OleDbCommand(sql, conn); conn.Open(); OleDbDataReader reader; reader = cmd.ExecuteReader();

            try
            {
                while (reader.Read())
                {
                    /// <summary>
                    ///SQL REFERENCE
                    ////// </summary>
                    //Game Name
                    sqlresult1 = reader.GetString(1).ToString();
                    //Compatibility
                    sqlresult3 = reader.GetString(3).ToString();
                    //Backup State
                    sqlresult4 = reader.GetString(4).ToString();
                    //Status
                    sqlresult5 = reader.GetString(5).ToString();
                    //Type
                    sqlresult6 = reader.GetString(6).ToString();
                    //Note
                    sqlresult7 = reader.GetString(7).ToString();
                    //Plus
                    sqlresult8 = reader.GetString(8).ToString();
                    //Moin
                    sqlresult9 = reader.GetString(9).ToString();
                    //Description
                    sqlresult10 = reader.GetString(10).ToString();
                    //Path
                    sqlresult11 = reader.GetString(11).ToString();
                    //Last Played
                    sqlresult12 = reader.GetString(12).ToString();
                    //Steam
                    sqlresult13 = reader.GetString(13).ToString();
                }
            }
            catch (Exception ex)
            { Console.WriteLine(ex.Message); return; }

            finally
            {
                reader.Close(); conn.Close();
            }
        }

        private void listbox_games_time(string gamename)
        {
            DataTable dtResults = new DataTable();
            dbConnection.Open();

            if (dbConnection.State == ConnectionState.Open)
            {
                OleDbCommand dbCommand = dbConnection.CreateCommand();
                dbCommand.CommandType = CommandType.Text;
                dbCommand.CommandText = "SELECT SUM([sessiontime]) AS TOTAL FROM timetrack WHERE gamelink = '" + gamename + "'";

                OleDbDataReader dbReader = dbCommand.ExecuteReader();

                if (dbReader.HasRows)
                    dtResults.Load(dbReader);

                dbReader.Close();
                dbConnection.Close();
            }

            Int32 timeresult;
            Int32.TryParse(dtResults.Rows[0]["TOTAL"].ToString(), out timeresult);

            sqlresultt1 = timeresult + " Minutes";
            sqlresultt2 = timeresult / 60 + " Hours";
        }

        private void total_games_time()
        {
            DataTable dtResults = new DataTable();
            dbConnection.Open();

            if (dbConnection.State == ConnectionState.Open)
            {
                OleDbCommand dbCommand = dbConnection.CreateCommand();
                dbCommand.CommandType = CommandType.Text;
                dbCommand.CommandText = "SELECT SUM([sessiontime]) AS TOTAL FROM timetrack";

                OleDbDataReader dbReader = dbCommand.ExecuteReader();

                if (dbReader.HasRows)
                    dtResults.Load(dbReader);

                dbReader.Close();
                dbConnection.Close();
            }

            Int32 timeresult;
            Int32.TryParse(dtResults.Rows[0]["TOTAL"].ToString(), out timeresult);

            sqlresultt3 = timeresult + " Minutes";
            sqlresultt4 = timeresult / 60 + " Hours";
        }

        private void datarefresh()
        {
            if (listbox_games.SelectedIndex != -1)
            {
                string gamename = listbox_games.SelectedItem.ToString();
                string sql = "SELECT * FROM gamecentral WHERE gamename = '" + gamename + "'";

                listbox_games_result(sql);
                listbox_games_time(gamename);

                label_gametitle.Content = sqlresult1;
                label_statusresult.Content = sqlresult5;
                label_typeresult.Content = sqlresult6;
                label_backupresult.Content = sqlresult4;
                label_compatibilityresult.Content = sqlresult3;
                textbox_descriptionresult.Text = sqlresult10;
                label_noteresult.Content = sqlresult7;
                textbox_plusresult.Text = sqlresult8;
                textbox_minusresult.Text = sqlresult9;
                label_playedresult.Content = sqlresult12;

                label_minutesresult.Content = sqlresultt1;
                label_hoursresult.Content = sqlresultt2;

                if (sqlresult11 == "NOT SET")
                {
                    image_playicon.Visibility = Visibility.Hidden;
                    label_playtext.Visibility = Visibility.Hidden;
                }
                else
                {
                    if (sqlresult11.Contains("steam"))
                    {
                        image_playicon.Visibility = Visibility.Hidden;
                    }
                    else
                    image_playicon.Visibility = Visibility.Visible;
                    label_playtext.Visibility = Visibility.Visible;
                }

                if (sqlresult11.Contains("steam"))
                {
                    image_steam.Visibility = Visibility.Visible;
                }
                else
                {
                    image_steam.Visibility = Visibility.Hidden;
                }

                if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + @"\Gamecover\" + gamename + ".jpg"))
                {
                    image_cover.Stretch = Stretch.Fill;
                    image_cover.Source = new BitmapImage(new Uri(AppDomain.CurrentDomain.BaseDirectory + @"\Gamecover\" + gamename + ".jpg"));
                }
                else
                {
                    image_cover.Stretch = Stretch.Uniform;
                    image_cover.Source = new BitmapImage(new Uri(AppDomain.CurrentDomain.BaseDirectory + @"\Resources\protogamez_logo.png"));
                }
            }
        }

        private void versioning()
        {
            string version = System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "version.int");
            label_RV.Content = version;
        }

        private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
        {
            DirectoryInfo dir = new DirectoryInfo(sourceDirName);
            DirectoryInfo[] dirs = dir.GetDirectories();

            if (!Directory.Exists(destDirName))
            {
                Directory.CreateDirectory(destDirName);
            }

            FileInfo[] files = dir.GetFiles();
            foreach (FileInfo file in files)
            {
                if (System.IO.Path.Combine(file.Name) != "Thumbs.db")
                {
                    string temppath = System.IO.Path.Combine(destDirName, file.Name);
                    file.CopyTo(temppath, true);
                }
            }

            if (copySubDirs)
            {
                foreach (DirectoryInfo subdir in dirs)
                {
                    string temppath = System.IO.Path.Combine(destDirName, subdir.Name);
                    DirectoryCopy(subdir.FullName, temppath, copySubDirs);
                }
            }
        }

        /// <summary>
        /// GLOBAL SOURCE CODE
        /// </summary>
        private void window_gamemode_Loaded(object sender, RoutedEventArgs e)
        {
            versioning();

            string versionI = System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + @"\version.int");
            string versionU = System.IO.File.ReadAllText(@"C:\Users\FCasaubon\Documents\Visual Studio 2012\Projects\Protogamez\Protogamez\publish\Application Files\Protogamez_0_0_0_0\version.int");

            if (versionI != versionU)
            {
                label_update.Visibility = Visibility.Visible;
            }
            else
            {
                label_update.Visibility = Visibility.Hidden;
            }

            total_games_time();
            label_totaltime.Content = sqlresultt3 + " / " + sqlresultt4;

            string sql = "SELECT * FROM gamecentral ORDER BY gamename";
            listbox_games_fill(sql);
        }

        private void textbox_search_KeyDown(object sender, KeyEventArgs e)
        {
            filter = "IP";
            label_filter.Content = "All Games";

            if (!Char.IsDigit((char)KeyInterop.VirtualKeyFromKey(e.Key)) & e.Key != Key.Back | e.Key == Key.Enter)
            {
                string sql = "SELECT * FROM gamecentral WHERE gamename LIKE '%" + textbox_search.Text + "%' ORDER BY gamename";
                listbox_games_fill(sql); listbox_games_fill(sql);
            }
        }

        private void image_search_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            textbox_search.Text = "";
            filter = "IP";
            label_filter.Content = "All Games";

            string sql = "SELECT * FROM gamecentral ORDER BY gamename";
            listbox_games_fill(sql); listbox_games_fill(sql);
        }

        private void listbox_games_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            datarefresh();
        }

        private void image_playicon_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            string gamename = listbox_games.SelectedItem.ToString();
            string sql = "SELECT * FROM gamecentral WHERE gamename = '" + gamename + "'";

            listbox_games_result(sql);

            try
            {
                var processStartInfo = new ProcessStartInfo(sqlresult11);
                processStartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(sqlresult11);
                Process gameProcess = Process.Start(processStartInfo);

                UserTimeDialog window = new UserTimeDialog(gamename);
                window.ShowDialog();
            }
            catch (Exception ex)
            { Console.WriteLine(ex.Message); return; }

            datarefresh();
        }

        private void imega_dbedit_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Process.Start(AppDomain.CurrentDomain.BaseDirectory + "\\Resources\\gamesdb.mdb");
        }

        private void image_addcover_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Process.Start(AppDomain.CurrentDomain.BaseDirectory + "\\Gamecover\\");
        }

        private void image_option_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            option window = new option();
            window.ShowDialog();
        }

        private void image_startbackup_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            listbox_games.IsEnabled = false;
            image_playicon.Opacity = 0.25;
            image_playicon.IsEnabled = false;
            image_steam.Opacity = 0.25;
                image_steam.IsEnabled = false;
            image_edit.Opacity = 0.25;
            image_edit.IsEnabled = false;
            textbox_search.IsEnabled = false;
            image_search.Opacity = 0.25;
            image_search.IsEnabled = false;
            image_startbackup.Opacity = 0.25;
            image_startbackup.IsEnabled = false;
            image_addcover.Opacity = 0.25;
            image_addcover.IsEnabled = false;
            imega_dbedit.Opacity = 0.25;
            imega_dbedit.IsEnabled = false;
            image_option.Opacity = 0.25;
            image_option.IsEnabled = false;
            image_filter.Opacity = 0.25;
            image_filter.IsEnabled = false;
            image_updatetop.Opacity = 0.25;
            image_updatetop.IsEnabled = false;

            label_backupstatus.Content = "Backup Running";


            Task backgroundDBTask = Task.Factory.StartNew(() =>
            {
                string sql = "SELECT * FROM gamecentral WHERE backupable = 'Yes' ORDER BY gamename";
                OleDbCommand cmd = new OleDbCommand(sql, conn); conn.Open(); OleDbDataReader reader; reader = cmd.ExecuteReader();

                try
                {
                    while (reader.Read())
                    {
                        /// <summary>
                        ///SQL REFERENCE
                        ////// </summary>
                        //Save Path
                        gamename = reader.GetString(1).ToString();
                        //Save Path
                        savepath = reader.GetString(2).ToString();

                        DirectoryCopy(savepath, Properties.Settings.Default.backuppath + @"\" + gamename + @"\", true);
                    }
                }
                catch (Exception ex)
                { Console.WriteLine(ex.Message); return; }

                finally
                {
                    reader.Close(); conn.Close();
                }
            });

            backgroundDBTask.ContinueWith((t) =>
            {
                listbox_games.IsEnabled = true;
                image_playicon.Opacity = 1;
                image_playicon.IsEnabled = true;
                image_steam.Opacity = 1;
                image_steam.IsEnabled = true;
                image_edit.Opacity = 1;
                image_edit.IsEnabled = true;
                textbox_search.IsEnabled = true;
                image_search.Opacity = 1;
                image_search.IsEnabled = true;
                image_startbackup.Opacity = 1;
                image_startbackup.IsEnabled = true;
                image_addcover.Opacity = 1;
                image_addcover.IsEnabled = true;
                imega_dbedit.Opacity = 1;
                imega_dbedit.IsEnabled = true;
                image_option.Opacity = 1;
                image_option.IsEnabled = true;
                image_filter.Opacity = 1;
                image_filter.IsEnabled = true;
                image_updatetop.Opacity = 1;
                image_updatetop.IsEnabled = true;

                label_backupstatus.Content = "Start Backup";

                MessageBox.Show("Backup of selected game has been completed");
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }

        private void image_edit_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            string gamename = listbox_games.SelectedItem.ToString();

            EditMode window = new EditMode(gamename);
            window.ShowDialog();

            datarefresh();
        }

        private void image_filter_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            textbox_search.Text = "";

            string sql = "";

            switch (filter)
            {
                case "AG":
                    filter = "IP";

                    sql = "SELECT * FROM gamecentral ORDER BY gamename";
                    listbox_games_fill(sql);

                    label_filter.Content = "All Games";
                    break;

                case "IP":
                    filter = "UF";

                    sql = "SELECT * FROM gamecentral WHERE gamestatus = 'In Progress' ORDER BY gamename";
                    listbox_games_fill(sql);

                    label_filter.Content = "In Progress Games";
                    break;

                case "UF":
                    filter = "US";

                    sql = "SELECT * FROM gamecentral WHERE gamestatus = 'Unfinished' ORDER BY gamename";
                    listbox_games_fill(sql);

                    label_filter.Content = "Unfinished Games";
                    break;

                case "US":
                    filter = "CO";

                    sql = "SELECT * FROM gamecentral WHERE gamestatus = 'Unstarted' ORDER BY gamename";
                    listbox_games_fill(sql);

                    label_filter.Content = "Unstarted Games";
                    break;

                case "CO":
                    filter = "AG";

                    sql = "SELECT * FROM gamecentral WHERE gamestatus = 'Completed' ORDER BY gamename";
                    listbox_games_fill(sql);

                    label_filter.Content = "Completed Games";
                    break;
            }
        }

        private void image_updatetop_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var processStartInfo = new ProcessStartInfo(AppDomain.CurrentDomain.BaseDirectory + @"\Protogamez Installer\Protogamez_Installer.exe");
            processStartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory + @"\Protogamez Installer\");
            Process gameProcess = Process.Start(processStartInfo);

            this.Close();
        }

        private void image_steam_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            string gamename = listbox_games.SelectedItem.ToString();
            string sql = "SELECT * FROM gamecentral WHERE gamename = '" + gamename + "'";

            listbox_games_result(sql);

            try
            {
                var processStartInfo = new ProcessStartInfo(sqlresult11);
                processStartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(sqlresult11);
                Process gameProcess = Process.Start(processStartInfo);

                UserTimeDialog window = new UserTimeDialog(gamename);
                window.ShowDialog();
            }
            catch (Exception ex)
            { Console.WriteLine(ex.Message); return; }

            datarefresh();
        }

        private void image_filter_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            filter = "IP";

            string sql = "SELECT * FROM gamecentral ORDER BY gamename";
            listbox_games_fill(sql); listbox_games_fill(sql);

            label_filter.Content = "All Games";
        }
    }
}
